<template>
  <div class="weather-impact">
    <div class="impact-content">
        <!-- 气象负荷相关性分析 -->
      <div class="charts-container">
        <div class="chart-section">
          <!-- 相关性概览卡片 -->
          <div v-if="correlationData" class="correlation-overview">
            <div class="correlation-cards">
              <div 
                v-for="(feature, key) in correlationData.correlation_analysis" 
                :key="key"
                class="correlation-card"
                :class="getCorrelationImpactClass(feature.impact_level)"
              >
                <div class="feature-name">{{ getFeatureName(key) }}</div>
                <div class="correlation-value">
                  {{ feature.pearson_correlation > 0 ? '+' : '' }}{{ feature.pearson_correlation }}
                </div>
                <div class="impact-level">{{ feature.impact_level }}</div>
                <div class="description">{{ feature.description }}</div>
              </div>
            </div>
          </div>
          
          <!-- 时间序列图 - 五个曲线 -->
          <div v-if="correlationData" class="time-series">
            <div :id="'timeSeriesChart'" class="chart fullscreen-chart"></div>
          </div>
          
          <!-- 统计摘要 -->
          <!-- <div v-if="correlationData" class="statistics-summary">
            <Descriptions :column="2" border>
              <DescriptionsItem label="分析天数">
                {{ correlationData.summary.total_days }} 天
              </DescriptionsItem>
              <DescriptionsItem label="分析期间">
                {{ correlationData.summary.analysis_period.start_date }} 至 {{ correlationData.summary.analysis_period.end_date }}
              </DescriptionsItem>
              <DescriptionsItem label="最强相关性">
                {{ getFeatureName(correlationData.summary.strongest_correlation[0]) }}: 
                {{ correlationData.summary.strongest_correlation[1] > 0 ? '+' : '' }}{{ correlationData.summary.strongest_correlation[1] }}
              </DescriptionsItem>
              <DescriptionsItem label="最弱相关性">
                {{ getFeatureName(correlationData.summary.weakest_correlation[0]) }}: 
                {{ correlationData.summary.weakest_correlation[1] > 0 ? '+' : '' }}{{ correlationData.summary.weakest_correlation[1] }}
              </DescriptionsItem>
            </Descriptions>
          </div> -->
        </div>
        </div>
    </div>
  </div>
</template>

<script>
// ECharts 通过全局插件注册，使用 this.$echarts
import { predictionAPI } from '@/utils/api'
import { 
  prepareDateForAPI, 
  getDatePickerOptions,
  getCurrentUTCDate 
} from '@/utils/timezone'
import { Descriptions, DescriptionsItem } from 'iview'

export default {
  name: 'WeatherImpact',
  components: {
    Descriptions,
    DescriptionsItem
  },
  data() {
    return {
      selectedDate: (() => {
        const today = new Date()
        const year = today.getFullYear()
        const month = String(today.getMonth() + 1).padStart(2, '0')
        const day = String(today.getDate()).padStart(2, '0')
        return new Date(`${year}-${month}-${day}`)
      })(),
      weatherData: {
        correlation_factors: []
      },
      // 使用统一的UTC日期配置
      dateOptions: getDatePickerOptions(),
      // 气象负荷相关性分析相关数据
      correlationDateRange: null,
      correlationLoading: false,
      correlationData: null,
      correlationCharts: {}
    }
  },
  mounted() {
    this.initCorrelationAnalysis()
    this.loadWeatherData()
  },
      beforeDestroy() {
      // 清理相关性分析图表
      Object.values(this.correlationCharts).forEach(chart => {
        if (chart && typeof chart.dispose === 'function') {
          chart.dispose()
        }
      })
    },
      methods: {
      // 初始化气象负荷相关性分析
      initCorrelationAnalysis() {
      // 设置默认日期范围为最近1年（不包括当天）
        const endDate = new Date()
      endDate.setDate(endDate.getDate() - 1) // 不包括当天
        const startDate = new Date()
      startDate.setDate(startDate.getDate() - 365) // 前1年
        
        this.correlationDateRange = [
          startDate.toISOString().split('T')[0],
          endDate.toISOString().split('T')[0]
        ]
      
      // 自动加载数据
      this.analyzeWeatherCorrelation()
      },
      
      // 分析气象负荷相关性
      async analyzeWeatherCorrelation() {
        if (!this.correlationDateRange || this.correlationDateRange.length !== 2) {
          this.$Message.warning('请选择日期范围')
          return
        }
        
        this.correlationLoading = true
        try {
          const response = await predictionAPI.getWeatherLoadCorrelation(
            this.correlationDateRange[0],
            this.correlationDateRange[1]
          )
          
          if (response.success) {
            this.correlationData = response.data
          console.log('接收到的数据:', this.correlationData)
            this.$nextTick(() => {
            this.renderTimeSeriesChart()
            })
            this.$Message.success('相关性分析完成')
          } else {
            this.$Message.error(response.message || '分析失败')
          }
        } catch (error) {
          console.error('相关性分析失败:', error)
          this.$Message.error('分析失败，请稍后重试')
        } finally {
          this.correlationLoading = false
        }
      },
      
    // 渲染时间序列图 - 五个曲线
    renderTimeSeriesChart() {
      const timeSeriesElement = document.getElementById('timeSeriesChart')
      if (!timeSeriesElement) {
        console.error('找不到时间序列图表容器元素')
        return
      }
      
      console.log('开始渲染时间序列图表...')
      console.log('图表容器尺寸:', timeSeriesElement.offsetWidth, 'x', timeSeriesElement.offsetHeight)
      
      // 确保容器有高度
      if (timeSeriesElement.offsetHeight === 0) {
        console.error('图表容器高度为0，设置最小高度')
        timeSeriesElement.style.height = '500px'
      }
        
        // 销毁旧图表
        if (this.correlationCharts['timeSeries']) {
          this.correlationCharts['timeSeries'].dispose()
        }
        
      const chart = echarts.init(timeSeriesElement)
        this.correlationCharts['timeSeries'] = chart
        
        const timeSeriesData = this.correlationData.time_series
      
      console.log('时间序列数据:', timeSeriesData)
      
      // 检查数据是否完整
      if (!timeSeriesData || !timeSeriesData.dates || !timeSeriesData.load) {
        console.error('时间序列数据不完整:', timeSeriesData)
        return
      }
        
        const option = {
          title: {
          text: '气象与负荷时间序列分析（前1年）',
          left: 'center',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold'
          }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
          },
          formatter: function(params) {
            let result = `日期: ${params[0].axisValue}<br/>`
            params.forEach(param => {
              let value = param.value
              let unit = ''
              if (param.seriesName === '平均负荷') {
                unit = ' MW'
              } else if (param.seriesName.includes('温度')) {
                unit = '°C'
              } else if (param.seriesName === '降水量') {
                unit = ' mm'
              } else if (param.seriesName === '相对湿度') {
                unit = '%'
              }
              result += `${param.seriesName}: ${value}${unit}<br/>`
            })
            return result
            }
          },
          legend: {
          data: ['平均负荷', '最高气温', '最低气温', '降水量', '相对湿度'],
          top: 40,
          textStyle: {
            fontSize: 14
          }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
          top: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: timeSeriesData.dates,
            axisLabel: {
            rotate: 45,
            fontSize: 12
          },
          name: '日期',
          nameLocation: 'middle',
          nameGap: 50
          },
          yAxis: [
            {
              type: 'value',
              name: '负荷 (MW)',
            position: 'left',
            axisLabel: {
              formatter: '{value}'
            },
            nameTextStyle: {
              fontSize: 14
            }
            },
            {
              type: 'value',
              name: '温度 (°C)',
              position: 'right',
            axisLabel: {
              formatter: '{value}'
            },
            nameTextStyle: {
              fontSize: 14
            }
            },
            {
              type: 'value',
              name: '降水量 (mm) / 湿度 (%)',
            position: 'right',
            offset: 80,
            axisLabel: {
              formatter: '{value}'
            },
            nameTextStyle: {
              fontSize: 14
            }
            }
          ],
          series: [
            {
            name: '平均负荷',
              type: 'line',
              yAxisIndex: 0,
            data: timeSeriesData.load,
            itemStyle: { color: '#ff6b6b' },
            lineStyle: { width: 3 },
            smooth: true,
            symbol: 'circle',
            symbolSize: 6
            },
            {
            name: '最高气温',
              type: 'line',
              yAxisIndex: 1,
              data: timeSeriesData.temp_max,
            itemStyle: { color: '#ffa726' },
            lineStyle: { width: 2 },
            smooth: true,
            symbol: 'diamond',
            symbolSize: 5
            },
            {
            name: '最低气温',
              type: 'line',
              yAxisIndex: 1,
              data: timeSeriesData.temp_min,
            itemStyle: { color: '#4ecdc4' },
            lineStyle: { width: 2 },
            smooth: true,
            symbol: 'triangle',
            symbolSize: 5
            },
            {
              name: '降水量',
              type: 'line',
              yAxisIndex: 2,
              data: timeSeriesData.precip,
            itemStyle: { color: '#45b7d1' },
            lineStyle: { width: 2, type: 'dashed' },
            smooth: true,
            symbol: 'rect',
            symbolSize: 4
            },
            {
            name: '相对湿度',
              type: 'line',
              yAxisIndex: 2,
              data: timeSeriesData.humidity,
            itemStyle: { color: '#96ceb4' },
            lineStyle: { width: 2 },
            smooth: true,
            symbol: 'circle',
            symbolSize: 4
            }
          ]
        }
        
      console.log('ECharts配置:', option)
      
      try {
        chart.setOption(option)
        console.log('时间序列图表渲染成功')
      } catch (error) {
        console.error('渲染时间序列图表失败:', error)
      }
      
      // 监听窗口大小变化，调整图表大小
      window.addEventListener('resize', () => {
        chart.resize()
      })
      },
      
      // 获取特征名称
      getFeatureName(key) {
        const nameMap = {
        'temp_max': '最高气温',
        'temp_min': '最低气温',
          'precip': '降水量',
        'humidity': '相对湿度'
        }
        return nameMap[key] || key
      },
      
      // 获取相关性影响程度样式类
      getCorrelationImpactClass(impactLevel) {
        const classMap = {
          '强相关': 'strong-correlation',
          '中等相关': 'medium-correlation',
          '弱相关': 'weak-correlation',
          '无相关': 'no-correlation'
        }
        return classMap[impactLevel] || 'no-correlation'
      },
      
      async loadWeatherData() {
      try {
        // 确保selectedDate是Date对象
        let selectedDate = this.selectedDate
        if (!(selectedDate instanceof Date)) {
          if (typeof selectedDate === 'string') {
            selectedDate = new Date(selectedDate)
          } else {
            selectedDate = new Date()
          }
          this.selectedDate = selectedDate
        }
        
        // 使用UTC标准化的日期格式
        const dateStr = prepareDateForAPI(selectedDate)
        
        const response = await predictionAPI.getWeatherImpact(dateStr)
        
        if (response.success) {
          const analysisData = response.data
          
          // 更新天气数据 - 使用动态计算的数据
          if (analysisData.weather_data) {
            this.weatherData.temperature = analysisData.weather_data.t_max || null
            this.weatherData.humidity = analysisData.weather_data.humidity || null
            this.weatherData.wind_speed = analysisData.weather_data.wind_speed || null
            this.weatherData.weather_type = analysisData.weather_data.weather_type || null
          }
          
          // 更新相关性数据 - 使用后端返回的动态相关性数据
          if (analysisData.correlation_coefficients) {
            const coeffs = analysisData.correlation_coefficients
            this.weatherData.correlation_factors = [
              {
                name: '最高温度',
                correlation: coeffs.max_temperature ? coeffs.max_temperature.toFixed(3) : '0.000',
                impact_level: this.getImpactLevel(coeffs.max_temperature || 0)
              },
              {
                name: '最低温度',
                correlation: coeffs.min_temperature ? coeffs.min_temperature.toFixed(3) : '0.000',
                impact_level: this.getImpactLevel(coeffs.min_temperature || 0)
              },
              {
                name: '湿度',
                correlation: coeffs.humidity ? coeffs.humidity.toFixed(3) : '0.000',
                impact_level: this.getImpactLevel(coeffs.humidity || 0)
              },
              {
                name: '降水量',
                correlation: coeffs.precipitation ? coeffs.precipitation.toFixed(3) : '0.000',
                impact_level: this.getImpactLevel(coeffs.precipitation || 0)
              }
            ]
          } else {
            // 如果没有相关性数据，显示警告
            console.warn('未获取到相关性系数数据，使用空数组')
            this.weatherData.correlation_factors = []
          }
        } else {
          throw new Error(response.message || '获取气象数据失败')
        }
      } catch (error) {
        console.error('加载气象数据失败:', error)
        this.$Message.error(error.message || '加载气象数据失败')
        throw error
      }
    },
    
    getImpactLevel(correlation) {
      const absCorr = Math.abs(correlation)
      if (absCorr > 0.7) return '强'
      if (absCorr > 0.4) return '中'
      return '弱'
    }
  }
}
</script>

<style scoped>
.weather-impact {
  height: 100vh;
      display: flex;
  flex-direction: column;
}

.impact-content {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  }
  
  .charts-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-section {
  flex: 1;
        display: flex;
  flex-direction: column;
  }
  
.correlation-overview {
  margin-bottom: 20px;
    }
    
.correlation-cards {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 15px;
    margin-bottom: 20px;
}
      
      .correlation-card {
        padding: 15px;
        border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
  text-align: center;
  transition: transform 0.3s ease;
}
        
.correlation-card:hover {
          transform: translateY(-2px);
        }
        
.correlation-card.strong-correlation {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
        }
        
.correlation-card.medium-correlation {
  background: linear-gradient(135deg, #feca57 0%, #ff9ff3 100%);
        }
        
.correlation-card.weak-correlation {
  background: linear-gradient(135deg, #48dbfb 0%, #0abde3 100%);
        }
        
.correlation-card.no-correlation {
  background: linear-gradient(135deg, #c8d6e5 0%, #8395a7 100%);
        }
        
        .feature-name {
          font-size: 16px;
          font-weight: bold;
          margin-bottom: 8px;
        }
        
        .correlation-value {
          font-size: 24px;
          font-weight: bold;
          margin-bottom: 5px;
        }
        
        .impact-level {
  font-size: 12px;
          opacity: 0.9;
  margin-bottom: 8px;
        }
        
        .description {
  font-size: 11px;
          opacity: 0.8;
  line-height: 1.3;
  }
  
.time-series {
  flex: 1;
    margin-bottom: 20px;
}

.fullscreen-chart {
          width: 100%;
  height: calc(100vh - 300px) !important;
  min-height: 600px;
  border: 1px solid #1a3c58;
  background: rgba(7, 19, 50, 0.6);
  }
  
  .statistics-summary {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .correlation-cards {
    grid-template-columns: 1fr;
  }
  
  .fullscreen-chart {
    height: calc(100vh - 400px) !important;
  }
}
</style> 